<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="__UI__/css/bs3/dpl.css" rel="stylesheet" type="text/css" />
<link href="__UI__/css/bs3/bui.css" rel="stylesheet" type="text/css" />
<link href="__UI__/css/style.css" rel="stylesheet" type="text/css" />
<link href="__UI__/uploadify/uploadify.css" rel="stylesheet" type="text/css">
<!--<link rel="stylesheet" href="https://cdn.webrtc-experiment.com/style.css">-->
<script src="__UI__/js/MediaStreamRecorder.js"></script>
<style type="text/css">

.conWrap {
	width:90%;
	margin:0px auto;
}

.control-group .controls{
	float:none;
	margin-bottom:40px;
}

.controls .con{
	width:90%;
	margin:20px auto 20px 130px;
	height:auto;
	line-height:30px;
	word-wrap: break-word; 
	word-break: normal;
}

.controls .cons{
	width:90%;
	margin:-24px auto 20px 120px;
	height:auto;
	min-height:30px;
	line-height:30px;
	word-wrap: break-word; 
	word-break: normal;
	overflow:hidden;
	float:left;
}

#tabbox {
	width:86%;
	overflow:hidden;
	margin:0 auto;
}

.tabs {
	width: 100%;
	height: 32px;
	margin-bottom:10px;
	margin-top:20px;
}

.tabs li {
	float:left;
	height:31px;
	line-height:31px;
	border:1px solid #EAEAEA;
	border-left:none;
	margin-bottom: -1px;
	background: #e0e0e0;
	overflow: hidden;
	position: relative;
	border-radius:5px;
	margin:0px 5px;
}

.tabs li a {
	display: block;
	padding: 0 20px;
}

.tabs li a:hover {
	background: #ccc;
}	

.tabs .thistab,.tabs .thistab a:hover,.tabs .thistab a:active {
	background: #fff;
	border:1px solid #EAEAEA;
}

.tab_conbox {
	border: 1px solid #EAEAEA;
	height:auto;
	overflow:hidden;
}

.tab_con {
	padding:12px;
	font-size: 14px;
	line-height:175%;
}

.voice {
	margin:40px auto 20px 120px;
}

.hint h4{
	margin:10px auto;
}

.hint ul{
	width:100%;
}

.hint ul li {
	display:inline-block;
	margin:0px 10px 10px 10px;
	height:40px;
	line-height:40px;
	color:#fff;
}
.news_input {
            border: 1px solid rgb(46, 189, 235);
            border-radius: 3px;
            font-size: 1em;
            outline: none;
            padding: .2em .4em;
            width: 60px;
            text-align: center;
}
select {
            vertical-align: middle;
            line-height: 1;
            padding: 2px 5px;
            height: auto;
            font-size: inherit;
            margin: 0;
}

.experiment {

	    border: 1px solid rgb(189, 189, 189);
	    margin: 1em 3em;
	    border-radius: .2em;
	    text-align: left;
}

button, input[type=button] {
	    -moz-border-radius: 3px;
	    -moz-transition: none;
            -webkit-transition: none;
	    background: #0370ea;
	    background: -moz-linear-gradient(top, #008dfd 0, #0370ea 100%);
	    background: -webkit-linear-gradient(top, #008dfd 0, #0370ea 100%);
	    border: 1px solid #076bd2;
	    border-radius: 3px;
	    color: #fff;
	    display: inline-block;
	    font-family: inherit;
	    font-size: .8em;
	    line-height: 1.3;
	    padding: 5px 12px;
	    text-align: center;
	    text-shadow: 1px 1px 1px #076bd2;
	    font-size: 1.5em;
}

button:hover, input[type=button]:hover {

	    background: rgb(9, 147, 240);
}

button:active, input[type=button]:active {

	    background: rgb(10, 118, 190);
}

button[disabled], input[type=button][disabled] {
	    background: none;
	    border: 1px solid rgb(187, 181, 181);
	    color: gray;
	    text-shadow: none;
}

</style>

<script type="text/javascript" src="__UI__/js/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="__UI__/js/jquery.SuperSlide.js"></script>
<script type="text/javascript" src="__UI__/voice/HZRecorder.js"></script>
<script type="text/javascript" src="__UI__/js/config.js"></script>
<script type="text/javascript" src="__UI__/js/bui.js"></script>
<script type="text/javascript" src="__UI__/js/Validform_v5.3.2_min.js"></script>

<script language="javascript">

var winID = null;
function openFullWindow(url,winname){
	var strFeatures = "left=0,screenX=0,top=0,screenY=0";  
	if (window.screen){
		var maxh = screen.availHeight-30;
		var maxw = screen.availWidth-10;
		strFeatures += ",height="+maxh;
		strFeatures += "innerHeight"+maxh;
		strFeatures += ",width="+maxw;
		strFeatures += "innerwidth"+maxw;
	}else{
		strFeatures +=",resizable"; 
	}
	winID = window.open(url,winname,strFeatures);
}

</script>
</head>
<body>

<div class="demo-content" style="margin-top:1%;">
    <div class="row" style="margin-left:10px;">
		<div style="text-align:center"><h2>{$scripts.scriptsname} - 场景演练</h2><hr></div>
        <div class="conWrap">
        	<a class="button button-primary" onClick="window.location.reload();" style="margin-bottom:20px;">刷新本页</a>
            <div class="hint">
            	<h4>操作提示</h4>
                <ul>
                	<li>1、点击开始响应，进入部门响应计时</li>
                    <li>2、响应提示，输入响应的文字说明</li>
                    <li>3、响应录音，点击麦克风，进入时间倒计时，进行部门响应录音，再点麦克风结束录音保存</li>
                    <li>4、点击提交响应，结束部门响应计时</li>
                </ul>
            </div>
        	<form id="J_Form" action="{:U('Home/Hint/edit')}" class="form-horizontal registerform" method="post" enctype="multipart/form-data">
                <ul class="tab_conbox" id="tab_conbox">
                    <li class="tab_con">
            			<div style="text-align:center"><h2>{$scene.scenename} - {:I('get.tid')}响应</h2><hr></div>
                        <div id="panel" class="" style="padding:10px;">
							<input name="sid" id="sid" type="hidden" value="{:I('get.sid')}">
							<input name="uid" id="uid" type="hidden" value="{:I('get.uid')}">
							<input name="mid" id="mid" type="hidden" value="{:I('get.mid')}">
							<input name="pid" id="pid" type="hidden" value="{:I('get.pid')}">
                            <input name="hid" id="hid" type="hidden" value="{:I('get.hid')}">
                            <input name="did" id="did" type="hidden" value="{:I('get.did')}">
                            <input name="rid" id="rid" type="hidden" value="{:I('get.rid')}">
                            <input name="department" id="tid" type="hidden" value="{:I('get.tid')}">
							<div class="control-group">
								<label class="control-label">响应提示</label>
								<div class="controls">
									<textarea name="hint" datatype="*" nullmsg="请输入响应提示！" data-tip="{text:'请输入响应提示'}" style="width:800px; height:150px; " id="add"></textarea>
								</div>
                            </div>
                            <div class="control-group" style="margin-top:40px;">
								<label class="control-label">响应录音</label>
								<div class="controls">
                                	<div id="voice"></div>
<script type="text/javascript">
	function  f_getURL(){
		var url = "{:U('Scripts/acceptfile')}";
		return url;
	}
	
	function f_getMAX(){
		return 60*60*1;
	}
	
	function f_getMIN(){
		return 1;
	}
	
	function f_complete(filename){
		$('#voice').append('<input name="voice" type="hidden" value="./Public/voice/'+filename+'">');
	}
</script>
<!---旧的录音strart--->
<!--<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="808" height="140" id="as_js" align="middle">
	<param name="allowScriptAccess" value="sameDomain" />
	<param name="movie" value="__UI__/voice/bbsRecorder.swf" />
	<param name="quality" value="high" />
	<param name="wmode" value="transparent">
	<param name="bgcolor" value="#cccccc" />
	<embed src="__UI__/voice/bbsRecorder.swf" vmode="transparent" quality="high" bgcolor="#cccccc" width="808" height="140" name="as-js" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>-->
<!--旧的录音end-->
<!--新的录音start-->
<section class="experiment" style="padding: 5px;">
            <label for="time-interval">时间间隔 (毫秒):</label>
            <input class="news_input"type="text" id="time-interval" value="5000">ms

            <br>
            <br> 录音类型:

            <select id="audio-recorderType" style="font-size:22px;vertical-align: middle;margin-right: 5px;">
                <option>[Best Available Recorder]</option>
                <option>MediaRecorder API</option>
                <option>WebAudio API (WAV)</option>
                <option>WebAudio API (PCM)</option>
            </select>
            <br>

            <input class="news_input" id="left-channel" type="checkbox" checked style="width:auto;">
            <label for="left-channel">如果选择了WebAudio API，则录制单声道音频</label>

            <br>
            <br>

            <button id="start-recording">开始</button>
            <button id="stop-recording" disabled>停止</button>

            <button id="pause-recording" disabled>暂停</button>
            <button id="resume-recording" disabled>恢复</button>

            <button id="save-recording" disabled>保存</button>
        </section>

        <section class="experiment">
            <div id="audios-container"></div>
        </section>
<!--新的录音end-->
								</div>
                            </div>
                            <div class="row actions-bar" style="background:none; border:0px;">
								<a class="button button-primary" id="start">开始响应</a>
								<button type="submit" class="button button-primary">提交响应</button>
							</div>
<script type="text/javascript">
	$(function () {
		$('#start').click(function(){
			var sid = $("#sid").val();
			var uid = $("#uid").val();
			var mid = $("#mid").val();
			var pid = $("#pid").val();
			var hid = $("#hid").val();
			var cid = {$cid};
			var did = $("#did").val();
			var rid = $("#rid").val();
			var tid = $("#tid").val();
			$.ajax({
				type:'post',
				url:'{:U("Home/Scripts/starts")}',
				dataType:'json',
				data:{sid:sid, uid:uid, mid:mid, pid:pid, hid:hid, cid:cid, did:did, rid:rid, department:tid},
				success:function(data){
					if(data.status == 'y'){
						$('#voice').append('<input id="zid" name="zid" type="hidden" value="'+data.id+'">');
						BUI.Message.Alert('响应开始！');
					}else{
						BUI.Message.Alert('响应失败！');
					}
				}
			});
		});
    });
	
	$(function(){
		$(".registerform").Validform({
			tiptype:function(msg,o,cssctl){
				var objtip=$("#msgdemo2");
				cssctl(objtip,o.type);
				objtip.text(msg);
			},
			ajaxPost:true,
			callback:function(data){
				if(data.status == 'y'){
					openFullWindow('{:U("Home/Drill/index",array("id"=>$scene[id],"sid"=>I("get.sid"),"pid"=>I("get.pid"),"bid"=>"scene","nid"=>"department","tid"=>I("get.tid")))}#scripts/drill','JS')
					top.topManager.closePage();
				}
			},
		});
	});
</script>
                    	</div>
                    </li>
				</ul>
            </form>
            <a class="button button-primary" onClick="window.location.reload();" style="margin-top:20px;">刷新本页</a>

		</div>
	</div>
</div>
</body>
</html>
<script>
            function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
                navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
            }

            var mediaConstraints = {
                audio: true
            };

            document.querySelector('#start-recording').onclick = function() {
                this.disabled = true;
                captureUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
            };

            document.querySelector('#stop-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.stop();
                mediaRecorder.stream.stop();

                document.querySelector('#pause-recording').disabled = true;
                document.querySelector('#start-recording').disabled = false;
            };

            document.querySelector('#pause-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.pause();

                document.querySelector('#resume-recording').disabled = false;
            };

            document.querySelector('#resume-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.resume();

                document.querySelector('#pause-recording').disabled = false;
            };

            document.querySelector('#save-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.save();

                // alert('Drop WebM file on Chrome or Firefox. Both can play entire file. VLC player or other players may not work.');
            };

            var mediaRecorder;

            function onMediaSuccess(stream) {
                var audio = document.createElement('audio');

                audio = mergeProps(audio, {
                    controls: true,
                    muted: true
                });
                audio.srcObject = stream;
                audio.play();

                audiosContainer.appendChild(audio);
                audiosContainer.appendChild(document.createElement('hr'));

                mediaRecorder = new MediaStreamRecorder(stream);
                mediaRecorder.stream = stream;

                var recorderType = document.getElementById('audio-recorderType').value;

                if (recorderType === 'MediaRecorder API') {
                    mediaRecorder.recorderType = MediaRecorderWrapper;
                }

                if (recorderType === 'WebAudio API (WAV)') {
                    mediaRecorder.recorderType = StereoAudioRecorder;
                    mediaRecorder.mimeType = 'audio/wav';
                }

                if (recorderType === 'WebAudio API (PCM)') {
                    mediaRecorder.recorderType = StereoAudioRecorder;
                    mediaRecorder.mimeType = 'audio/pcm';
                }

                // don't force any mimeType; use above "recorderType" instead.
                // mediaRecorder.mimeType = 'audio/webm'; // audio/ogg or audio/wav or audio/webm

                mediaRecorder.audioChannels = !!document.getElementById('left-channel').checked ? 1 : 2;
                mediaRecorder.ondataavailable = function(blob) {
                    var a = document.createElement('a');
                    a.target = '_blank';
                    a.innerHTML = 'Open Recorded Audio No. ' + (index++) + ' (Size: ' + bytesToSize(blob.size) + ') Time Length: ' + getTimeLength(timeInterval);

                    a.href = URL.createObjectURL(blob);

                    audiosContainer.appendChild(a);
                    audiosContainer.appendChild(document.createElement('hr'));
                };

                var timeInterval = document.querySelector('#time-interval').value;
                if (timeInterval) timeInterval = parseInt(timeInterval);
                else timeInterval = 5 * 1000;

                // get blob after specific time interval
                mediaRecorder.start(timeInterval);

                document.querySelector('#stop-recording').disabled = false;
                document.querySelector('#pause-recording').disabled = false;
                document.querySelector('#save-recording').disabled = false;
            }

            function onMediaError(e) {
                console.error('media error', e);
            }

            var audiosContainer = document.getElementById('audios-container');
            var index = 1;

            // below function via: http://goo.gl/B3ae8c
            function bytesToSize(bytes) {
                var k = 1000;
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                if (bytes === 0) return '0 Bytes';
                var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10);
                return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
            }

            // below function via: http://goo.gl/6QNDcI
            function getTimeLength(milliseconds) {
                var data = new Date(milliseconds);
                return data.getUTCHours() + " hours, " + data.getUTCMinutes() + " minutes and " + data.getUTCSeconds() + " second(s)";
            }

            window.onbeforeunload = function() {
                document.querySelector('#start-recording').disabled = false;
            };

//文件保存，异步上传
function uploadPHPserver(blob){

	var file = new File([blob],'msr-' + (new Date).toISOString().replace(/:|\./g,'-') + '.wav',{ type: 'audio/wav'});

	var formdata = new FormData();
	formdata.append('audio-filename',file.name);
	formdata.append('audio-blob',file);

	makeXMLHttpRequest('{:U("Scripts/h5acceptfile")}',formdata,function(){
			 BUI.Message.Alert('保存完成!');
			 f_complete(file.name);

	});

}

function makeXMLHttpRequest(url,data,callback){
      var request = new XMLHttpRequest();
      request.onreadystatechange = function(){

           if (request.readyState == 4 && request.status == 200){
                    callback();
	   } 
      
      }

      request.open('POST', url);
      request.send(data);
}

        </script>
